import { useAuthStore } from '@/stores/auth'
import { useNotificationStore } from '@/stores/components/notification'

import i18n from '@/i18n'


export const handleError = (err) => {
  const authStore = useAuthStore()
  const notificationStore = useNotificationStore()

  if (!err.response) {
    notificationStore.showNotification({
      type: 'error',
      message:
        'Please check your internet connection or wait until servers are back online.',
    })
  } else {
    console.log('err.response.data.errors', err.response)

    if (err.response.data.detail) {
      // Show a notification per error
      if (err.response.data.detail == 'Could not validate credentials') {
        showError("errors.invalid_credentials")
        authStore.logout()
      } else {
        showError("errors."+err.response.data.detail)
      }
    } else if (
      err.response.data &&
      (err.response.statusText === 'Unauthorized' ||
        err.response.data === ' Unauthorized.')
    ) {
      // Unauthorized and log out
      const msg = err.response.data.message
        ? err.response.data.message
        : 'Unauthorized'

      showToaster(msg)
      // authStore.logout()
    } else if (err.response.data.error) {
      if (typeof err.response.data.error == 'boolean') 
        showError(err.response.data?.message)
      else showError(err.response.data.error)
    } else {
      showToaster(err.response.data.message || err.response.data, false)
    }
  }
}

export const showError = (error) => {
  switch (error) {
    case 'invalid_credentials':
      showToaster('errors.invalid_credentials')
      break

    default:
      showToaster(error)
      break
  }
}

export const showToaster = (msg, _t = true) => {
  const { t } = i18n.global

  const notificationStore = useNotificationStore()

  notificationStore.showNotification({
    type: 'error',
    message: _t ? t(msg) : msg,
  })
}
